#include <stdio.h>
#include <stdlib.h>

typedef struct node *Nodeptr;
typedef struct node {
  int i;
  Nodeptr next;
} Node;

int erase(Nodeptr *head, Nodeptr element)
{
  if(*head == NULL)
    return 0;
  Nodeptr iter = *head;
  //if the first element will be erased
  if(element == *head){
    *head = (*head)->next;
    printf("%d has been deleted...\n",element->i);
    free(element);
  }
  else {
    //searching and updating the preceding node
    while(iter->next != element && iter->next != NULL) //end of linked list
      iter = iter->next;

    if(iter->next == NULL) //not find in linked list
      return 0;
    else {//erase element
      iter->next = iter->next->next;
      printf("%d has been deleted...\n",element->i);
      free(element);
    }
  }
  return 1;
}
//ith item in the list, NULL if out of range
Nodeptr at(Nodeptr head,int i)
{
  int j;
  for(j = 0;j<i;j++){
    if(head != NULL)
      head = head->next;
    else
      return NULL;
  }
  return head;
}
void recursive_reverse(Nodeptr *head)
{
  Nodeptr curr;
  Nodeptr succ;
  if(*head == NULL)
    return;
  curr = *head;
  succ = curr->next;
  if(succ == NULL) //basis
    return;
  recursive_reverse(&succ); //recursive 
  curr->next->next = curr;
  curr->next = NULL;//trick 1 for old head's next
  *head = succ;//trick 2 for updating new head
}
//iterative
int reverse(Nodeptr *head)
{
  Nodeptr pre = NULL;
  Nodeptr curr = *head;
  Nodeptr succ;
  while(curr != NULL) { //ganrantee curr has a next
    succ = curr->next;
    curr->next = pre;
    pre = curr;
    curr = succ;
  }
  *head = pre;
  return 1;
}

void push_front(Nodeptr *head,int i)
{
  Nodeptr tmp = (Nodeptr)malloc(sizeof(Node) );
  tmp->i = i;
  tmp->next = *head;
  *head = tmp;
  return;
}

void print(Nodeptr *head)
{
  Nodeptr iter = *head;
  while(iter != NULL) {
    printf("%d\t",iter->i);
    iter = iter->next;
  }
  puts("");
}
int clear(Nodeptr *head)
{
  Nodeptr tmp;
  while(*head != NULL) {
    tmp = *head;
    *head = (*head)->next;
    printf("%d has been deleted...\n",tmp->i);
    free(tmp);
  }
  return 1;
}
int main(int argc, char *argv[])
{
  int i;
  Nodeptr head = NULL;
  //build singly-linked-list
  for(i=argc-1;i>=1;--i){
    push_front(&head,atoi(argv[i]));
  }
  

  print(&head);
  //op
  recursive_reverse(&head);
  print(&head);

  clear(&head);

  print(&head);
  return 0;
}
